const inflate=require('pako').inflate

class Lib {
    heartbeatInterval
    heartbeat

    constructor(roomId) {
        this.wws_url = 'wss://broadcastlv.chat.bilibili.com/sub'
        this.heartbeat = Buffer.from([0x00, 0x00, 0x00, 0x1f, 0x00, 0x10, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x01, 0x5b, 0x6f, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x20, 0x4f, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x5d])
        this.heartbeatInterval = 60000
        this.roomId = roomId
    }

    get_ws_info() {
        let reg_datas = []
        let data = JSON.stringify({
            "uid": Number(Math.floor(Math.random() * 1000000000000000)),
            "roomid": Number(this.roomId),
            "protover": 1
        }).replace(' ', '')

        data = this.encode(data)

        // console.log(data)
        reg_datas.push(data)
        return {ws_url: this.wws_url, login_data: reg_datas}
    }

    encode(data) {
        let buf = Buffer.alloc(data.length + 16)
        buf.writeInt32LE(data.length + 16, 3)
        buf.writeInt32LE(16, 5)
        buf.writeInt32LE(1, 7)
        buf.writeInt32LE(7, 11)
        buf.writeInt32LE(1, 15)
        buf.write(data, 16)
        return buf
    }

    decode_msg(buffer) {
        const arr = new Uint8Array(buffer);
        const view = new DataView(arr.buffer);
        const packs = [];
        let offset = 0;
        while (offset < arr.byteLength) {
            const protocol = view.getInt16(6 + offset);
            const type = view.getInt32(8 + offset);
            if (type === 5) {
                const section = arr.slice(offset + view.getInt16(4 + offset), view.getInt32(offset) + offset);
                if (protocol === 0) {
                    packs.push(JSON.parse(new TextDecoder().decode(section)));
                }
                if (protocol === 2) {
                    packs.push(this.decode_msg(inflate(section)));
                }
            }
            offset += view.getInt32(offset);
        }
        // console.log(JSON.stringify(packs))
        return packs;
    }
}

exports = module.exports = Lib
